import { appStore } from '@renderer/store/modules/app'
import { BlockIndex } from '@renderer/types/game'
import { increaseIndexDimension } from '@renderer/utils/game'
import { ref, watch } from 'vue'

export default function useClickEvent (props) {
  const { removeBlock, switchBlock } = appStore
  const lastClickBlock = ref<BlockIndex | null>(null)
  const useSkill = (index: number) => {
    const { canUseSkill, gridSize } = appStore
    const { currentSkill } = props
    if (!canUseSkill || !currentSkill) return
    const { row, col } = increaseIndexDimension(index, gridSize)
    if (currentSkill === 'remove') {
      removeBlock({ row, col })
    } else if (currentSkill === 'switch') {
      const lastIndex = lastClickBlock.value
      if (!lastIndex) {
        lastClickBlock.value = { row, col }
        return
      }
      if (lastIndex.row === row && lastIndex.col === col) {
        lastClickBlock.value = null
        return
      }
      switchBlock([lastClickBlock.value, { row, col }])
      lastClickBlock.value = null
    }
  }

  const isActive = (index: number) => {
    const lastIndex = lastClickBlock.value
    if (!lastIndex) return false
    const { gridSize } = appStore
    const { row, col } = increaseIndexDimension(index, gridSize)
    return lastIndex.row === row && lastIndex.col === col
  }

  watch(() => props.currentSkill, (val) => {
    if (val !== 'switch') {
      lastClickBlock.value = null
    }
  })

  return {
    useSkill,
    isActive
  }
}
